package com.hegongda.okcmall.product.web;

import com.hegongda.okcmall.product.entity.CategoryEntity;
import com.hegongda.okcmall.product.service.CategoryService;
import com.hegongda.okcmall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
     修改页面后自动刷新
      1、引入dev-tool jar
      2、ctrl+shift+F9 重新build
 */
/**
 * @author liueidong
 * @create 2021-02-27 22:21
 */
@Controller
public class WebPage {

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedissonClient redissonClient;

    @GetMapping({"/","/index.html"})
    public String index(Model model){
        // 需要查询商品的一级分类
        List<CategoryEntity> categoryEntities = categoryService.queryCategoryLevel();
        model.addAttribute("categorys", categoryEntities);
        return "index.html";
    }

    @GetMapping("/index/json/catalog.json")
    @ResponseBody
    public Map<String,List<Catelog2Vo>> getCatelog2(){
        return categoryService.getCatelog2();
    }

    /*
        RLock 实现了 juc中的Lock，当创建锁的时候自动设置了过期时间，并会根据业务的执行时间自动进行续命，当业务执行
        完毕后，即使没有执行释放锁的操作，锁也会因为过期而被释放
     */
    @GetMapping("/redisson")
    @ResponseBody
    public String get(){
        RLock lock = redissonClient.getLock("lockA");

        lock.lock();
        try {
            System.out.println("执行业务逻辑" + Thread.currentThread().getName());
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return "hello";
    }
}